<?php

declare(strict_types=1);

namespace EthanZ\HyperfExt\Middleware;

use EthanZ\HyperfExt\Utils\Tools;
use Hyperf\Amqp\Producer;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use EthanZ\HyperfExt\Common\TraceEntity;

class LogMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $requestLogEnable = config('request_log_enable', env('REQUEST_LOG_ENABLE'));
        if (1) {
            $body = $request->getParsedBody();
            $header = $this->getHeader($request->getHeaders());
            $log  = [
                'log_type'    => 'api_request_log',
                'datetime'    => date('Y-m-d H:i:s', time()),
                'app_id'      => env('APP_ID'),
                'app_name'    => env('APP_NAME'),
                'method'      => $request->getMethod(),
                'path'        => $request->getRequestTarget(),
                'agent'       => !empty($request->getHeader('User-Agent')) ? $request->getHeader('User-Agent')[0] : '',
                'body'        => json_encode($body),
                'user_id'     => isset($body['userId']) ? $body['userId'] : 0,
                'admin_id'    => isset($body['__adminId']) ? $body['__adminId'] : 0,
                'ip'          => Tools::getIp(),
                'request_time'=> time()
            ];
            $log = array_merge($log,$header);
            //前后端日志分开记录
            if (stristr($log['path'],'/admin/')){
                $log['log_type'] = 'admin_request_log';
            }
            echo json_encode($log)."\n";
        }

        return $handler->handle($request);
    }

    /**
    * 处理header数据
    *
    * access public
    * creatBy zhou
    * created 2022/8/30
    */
    public function getHeader($header)
    {
        $arr = [];
        foreach ($header as $key=> $item){
            $arr['header_'.str_replace('-','_',$key)] = $item[0] ?? '';
        }
        return $arr;
    }
}
